<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of browser
 *
 * @author Andriy
 */
class Browser
{
    protected $_proxy = null;
    
    protected $_cookie = null;
    
    protected $_ajax_header = array(
        'Host' => 'digg.com',
        'User-Agent' => 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0) Gecko/20100101 Firefox/4.0',
        'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',//'application/json, text/javascript, */*; q=0.01',
        'Accept-Language' => 'uk,ru;q=0.8,en-us;q=0.5,en;q=0.3',
        'Accept-Encoding' => 'gzip, deflate',
        'Accept-Charset' => 'windows-1251,utf-8;q=0.7,*;q=0.7',
        'Keep-Alive' => '115',
        'Connection' =>	'keep-alive',
        'Content-Type' => 'application/x-www-form-urlencoded; charset=UTF-8',
        'X-Requested-With' => 'XMLHttpRequest',
        'Referer' => 'http://westua.net/',
        'Content-Length' => '200',
        'Pragma' => 'no-cache',
        'Cache-Control' => 'no-cache'
    );

	protected $_header = array(
		'User-Agent' => 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.76 Safari/537.36',
		'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
		'Referer' => 'http://hetzner.com/',
		'Pragma' => 'no-cache',
		'Cache-Control' => 'no-cache'
	);


    public function get( $url,  $post_data = null, $is_ajax = false )
    {
	    sleep(1);

        $ch = curl_init();
        curl_setopt( $ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/534.30 (KHTML, like Gecko) Chrome/12.0.742.122 Safari/534.30" );
        curl_setopt( $ch, CURLOPT_URL, $url );
        
        if( !$this->_cookie )
        {
            $this->_cookie = tempnam ("tmp", "CURLCOOKIE");
        }
        curl_setopt( $ch, CURLOPT_COOKIEJAR, $this->_cookie );
        curl_setopt( $ch, CURLOPT_COOKIEFILE, $this->_cookie );
        
        curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
        curl_setopt( $ch, CURLOPT_ENCODING, "" );
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
        curl_setopt( $ch, CURLOPT_AUTOREFERER, true );
        
        if( $post_data )
        {
            curl_setopt($ch, CURLOPT_POST, 1); 
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data); 
        }
        
        if( $is_ajax )
        {
            curl_setopt( $ch, CURLOPT_HTTPHEADER, $this->_ajax_header);
        }
        
        if( $this->_proxy )
        {
            curl_setopt( $ch, CURLOPT_HTTPPROXYTUNNEL, 1 );
            curl_setopt( $ch, CURLOPT_PROXY, $this->_proxy->getProxy() ); 
        }
        
        $content = curl_exec( $ch );
//        $status = curl_getinfo($ch,CURLINFO_HTTP_CODE); 
//        print_r($status); echo "<br />";
        curl_close ( $ch );

	    if($this->_cookie)
		    @unlink($this->_cookie);
        
        return $content;
    }

	/**
	 * @param array $aUrl
	 * @return array $url as key, value as html
	 */
	public function multiQuery(array $aUrl)
	{
        if(PHP_OS === 'WINNT' || true)
            return $this->windowsMultiQuary($aUrl);

		$mh = curl_multi_init();

		$ch = array();
		foreach($aUrl as $i => $url)
		{
			$ch[$url] = curl_init();

			curl_setopt( $ch[$url], CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/534.30 (KHTML, like Gecko) Chrome/12.0.742.122 Safari/534.30" );
			curl_setopt( $ch[$url], CURLOPT_URL, $url );
			curl_setopt( $ch[$url], CURLOPT_FOLLOWLOCATION, true );
			curl_setopt( $ch[$url], CURLOPT_CONNECTTIMEOUT, 0 );
			curl_setopt( $ch[$url], CURLOPT_DNS_CACHE_TIMEOUT, 120 );
			curl_setopt( $ch[$url], CURLOPT_ENCODING, "" );
			curl_setopt( $ch[$url], CURLOPT_RETURNTRANSFER, true );
			curl_setopt( $ch[$url], CURLOPT_AUTOREFERER, true );
			curl_setopt( $ch[$url], CURLOPT_HEADER, 0);
			curl_setopt( $ch[$url], CURLOPT_HTTPHEADER, $this->_header);

			curl_multi_add_handle($mh, $ch[$url]);
		}

		$active = null;
		do {
			$mrc = curl_multi_exec($mh, $active);
		} while ($mrc == CURLM_CALL_MULTI_PERFORM);

		while ($active && $mrc == CURLM_OK)
		{
			// если какой-либо поток готов к действиям
			if (curl_multi_select($mh) != -1)
			{
				// ждем, пока что-нибудь изменится
				do
				{
					$mrc = curl_multi_exec($mh, $active);
					// получаем информацию о потоке
					$info = curl_multi_info_read($mh);
					// если поток завершился
					if ($info['msg'] == CURLMSG_DONE) {
						$h = $info['handle'];exit;
						// ищем урл страницы по дескриптору потока в массиве заданий
						$url = array_search($h, $ch);
						// забираем содержимое
						$ch[$url] = curl_multi_getcontent($h);
						// удаляем поток из мультикурла
						curl_multi_remove_handle($mh, $h);
						// закрываем отдельное соединение (поток)
						curl_close($h);
					}
				}
				while ($mrc == CURLM_CALL_MULTI_PERFORM);
			}
		}

		return $ch;
	}

    public function setProxy( Proxy $proxy )
    {
        $this->_proxy = $proxy;
    }

    public function windowsMultiQuary(array $aUrl)
    {
        $aResult = array();
        foreach($aUrl as $key => $url)
        {
            $aResult[$url] = $this->get($url);
        }

        return $aResult;
    }
    
}

?>
